import React, { Component, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import router from 'umi/router';
import styles from './index.less';
import Region from './distributionModal';
import DeliveryModal from './deliveryModal';
import SelectedImage from '@/components/plugins/selectImage/index';
import { Modal, Card, Switch, Input, Radio, Checkbox, Form, Button, message, Spin, Row, Col,List, Tag,Icon,Upload,InputNumber,Popconfirm,Table } from 'antd';

const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const namespace = 'sameCityDelivery'
@Form.create()
class Express extends Component {
  state = {
    currenrCenter:null,
    areaList: [
      {
        Shape:1,
        Radius:1,
        Center:[116.433322, 39.900255],
        AreaName: undefined,
        Color: 'magenta',
        FreightFee: undefined,
        MinOrderFee: undefined,
        Paths:[
          [116.391262,39.920163],
          [116.403322,39.920255],
          [116.413879,39.920492],
          [116.414737,39.89255],
          [116.402292,39.892353],
          [116.391734,39.892155]
        ]
      }
    ],
    polygonList:[],
    polyEditorList:[],
    areaType:1,
    currentIndex:0,
    Address:'',
    colorList:["magenta", "red", "volcano", "orange", "gold", "green", "cyan", "blue", "geekblue", "purple"],
    colors:["#FFADD2", "#ffa39e", "#ffbb96", "#ffd591"," #ffe58f", "#b7eb8f", "#87e8de", "#91d5ff", "#adc6ff", "#d3adf7"],
    bgcolors:["#FFADD2", "#ffa39e", "#ffbb96", "#ffd591"," #ffe58f", "#b7eb8f", "#87e8de", "#91d5ff", "#adc6ff", "#d3adf7"],
    // bgcolors:["#FFF0F6", "#fff1f0", "#fff2e8", "#fff7e6"," #fffbe6", "#f6ffed", "#e6fffb", "#e6f7ff", "#f0f5ff", "#f9f0ff"]
    paginationProps: {
      showSizeChanger: false,
      showQuickJumper: false,
      showTotal: total => `共 ${total} 条记录`,
      pageSize: 5,
      total: 0,
      pageIndex: 1,
    },
  }

  componentWillMount() {
    // this.getconfig();
    // this.GetFreightTemplateWithPage();
    this.map=null;
    window.Isoption = false;
  }

  componentDidMount(){
    window.Isoption = true;
    this.newMap(()=>{
      this.getconfig();
    });
    this.GetDeliveryManPageList();
  }

  //获取配送员列表
  GetDeliveryManPageList = () => {
    const { dispatch, form} = this.props;
    const { paginationProps } = this.state;
    dispatch({
      type: 'localdelivery/GetDeliveryManPageList',
      payload: {
        PageIndex: paginationProps.pageIndex,
        PageSize: paginationProps.pageSize
      },
      callBack: {
          success: res => {
              if(res.Code===0) {
                  console.log(res)
                  this.setState({
                    paginationProps: { ...this.state.paginationProps, total: res.Data.Total }
                  })
              }
          },
          error: res=> {
              message.error(res.Msg)
          }
      }
    })
  }

  newMap = (callback) => {
    this.map = new AMap.Map('mapContainer', {
      center:[116.46,39.92],
      zoom:11
    });
    let scale = new AMap.Scale({
        visible: true
    });
    let toolBar = new AMap.ToolBar({
        visible: true
    });
    this.map.addControl(scale);
    this.map.addControl(toolBar);
    this.map.getCity( function(info){
        console.log(info)
    });
   this.getAddress(callback)
  }

  getAddress = (callback) => {
     const {dispatch,form} = this.props;
     const {areaList} = this.state;
        dispatch({
            type:"sameCityDelivery/GetIntraCityAddress",
            callback:{
              success:(data)=>{
                if(data.Code==0&&data.Data&&data.Data.Lng){
                  this.map.setCenter([data.Data.Lng, data.Data.Lat]); //设置地图中心点
                  areaList[0].Center=[data.Data.Lng, data.Data.Lat];
                  this.setState({
                    currenrCenter:[data.Data.Lng, data.Data.Lat],
                    areaList
                  },()=>{
                    callback()
                  })
                }else{
                  let Center=this.map.getCenter();
                  areaList[0].Center=[Center.lng, Center.lat];
                  this.setState({
                    currenrCenter:[Center.lng, Center.lat],
                    areaList
                  })
                }
              }
            }
        })
  }

  setExpressConfig = (checked) => {
    if (checked) {
      this.openExpress();
    } else {
      this.CloseExpress();
    }
    //this.getconfig();
  }

  openExpress = () => {
    const { dispatch } = this.props;
    dispatch({
      type: `${namespace}/OpenSameCityDelivery`,
      callback: {
        success: (data) => {
          message.success("已开启");
         // this.getconfig()
         const{sameCityConfig} = this.props;
         dispatch({
          type:`${namespace}/saveGetSameCityConfig`,
          payload:{
            ...sameCityConfig,
            Enable:true
          }
         })
        },
        error: (data) => {
          message.error("开启失败：" + data.Msg);
        }
      }
    });
  }

  CloseExpress = () => {
    const { dispatch } = this.props;
    dispatch({
      type: `${namespace}/CloseSameCityDelivery`,
      callback: {
        success: (data) => {
          message.success("已关闭");
          //this.getconfig()
          const{sameCityConfig} = this.props;
         dispatch({
          type:`${namespace}/saveGetSameCityConfig`,
          payload:{
            ...sameCityConfig,
            Enable:false
          }
         })
        },
        error: (data) => {
          message.error("关闭失败：" + data.Msg);
        }
      }
    });
  }

  getconfig = () => {
    const { dispatch } = this.props;
    const { areaList } = this.state;
    let that=this;
    dispatch({
      type: `${namespace}/GetSameCityConfig`,
      param: { p: Math.random() },
      callback: {
        success:(data) => {
          //consoconsole.log(data,99)
          let cPayment = []
          if (data.Data.Config.IsSupportCOD) {
            cPayment.push(2)
          }
          if (data.Data.Config.IsSupportOnlinePay) {
            cPayment.push(1)
          }
          this.props.form.setFieldsValue({
            Payment:cPayment,
            SendType:data.Data.Config.SupportDelivery||[1],
            Address:data.Data.Config.AddressName,
            AreaType:data.Data.Config.AreaType
          })
          if(data.Data.Config.AreaType==1){
            if(data.Data.Config.AreaConfig&&data.Data.Config.AreaConfig.length){
              areaList.length=0;
              data.Data.Config.AreaConfig.forEach((v,i)=>{
                areaList.push({
                  Shape:v.Shape||1,
                  Center:v.Center,
                  Radius:v.Radius/1000,
                  AreaName: v.AreaName,
                  Color: v.Color,
                  FreightFee: v.FreightFee||'',
                  MinOrderFee: v.MinOrderFee||'',
                  Paths:v.Paths
                })
              })
              this.props.form.setFieldsValue({
                Shape: data.Data.Config.AreaConfig[0].Shape
              })
              if(data.Data.Config.AreaConfig[0].Radius){
                setTimeout(()=>{
                  this.props.form.setFieldsValue({
                    Radius: data.Data.Config.AreaConfig[0].Radius/1000
                  })
                },300)
              }
            }
          }else if(data.Data.Config.AreaType==2){
            if(data.Data.Config.DistanceConfig&&data.Data.Config.DistanceConfig.Areas&&data.Data.Config.DistanceConfig.Areas.length){
              areaList.length=0;
              data.Data.Config.DistanceConfig.Areas.forEach((v,i)=>{
                areaList.push({
                  Shape:v.Shape||1,
                  Center:v.Center,
                  Radius:v.Radius/1000,
                  AreaName: v.AreaName,
                  Color: v.Color,
                  FreightFee: v.FreightFee,
                  MinOrderFee: v.MinOrderFee,
                  Paths:v.Paths,
                  FirstDistance:data.Data.Config.DistanceConfig.FirstDistance,
                  FirstFee:data.Data.Config.DistanceConfig.FirstFee,
                  AdditionalDistance:data.Data.Config.DistanceConfig.AdditionalDistance,
                  AdditionalFee:data.Data.Config.DistanceConfig.AdditionalFee
                })
              })
              this.props.form.setFieldsValue({
                Shape: data.Data.Config.DistanceConfig.Areas[0].Shape,
              })
              if(data.Data.Config.DistanceConfig.Areas[0].Radius){
                setTimeout(()=>{
                  this.props.form.setFieldsValue({
                    Radius: data.Data.Config.DistanceConfig.Areas[0].Radius/1000,
                  })
                },300)
              }
            }
          }else{
            this.props.form.setFieldsValue({
              SendRangeName : data.Data.Config.SampleConfig.Name,
              SendRangeDesc : data.Data.Config.SampleConfig.Desc,
              SendRangePic : data.Data.Config.SampleConfig.AreaImage,
              MinPrice : data.Data.Config.SampleConfig.MinOrderFee,
              SendFree: data.Data.Config.SampleConfig.FreightFee,
            })
            this.setState({
              imageUrl:data.Data.Config.SampleConfig.AreaImage
            })
          }
          this.setState({ Payment: cPayment,Address:data.Data.Config.AddressName,areaList,areaType:data.Data.Config.AreaType },()=>{
            const {areaType} = this.state;
            if(areaType==1||areaType==2){
              this.newPolygon(0)
            }
          })
        }
      }
    });
  }

  handleSubmit = () => {
    const { dispatch,form } = this.props;
    let values=form.getFieldsValue();
    //console.log(values)
    //return;
    if(!values.Payment.length){
      return;
    }
   // form.validateFields((err, values) => {
      //console.log(values)
      if (values.Payment) {
        let param={};
        let IsSupportOnlinePayIndex = values.Payment.findIndex(item => item == 1)
        if (IsSupportOnlinePayIndex > -1) {
          param = {...param, SupportOnlinePay: true }
        } else {
          param = { ...param,SupportOnlinePay: false }
        }
        let IsSupportCODIndex = values.Payment.findIndex(item => item == 2)
        if (IsSupportCODIndex > -1) {
          param = {  ...param,SupportCOD: true }
        } else {
          param = { ...param, SupportCOD: false }
        }
        dispatch({
          type: `${namespace}/SaveSameCitySupportPay`,
          payload: param,
          callback: {
            success: (data) => {
              message.success("保存成功");
            },
            error: (data) => {
              message.error("保存失败：" + data.Msg);
            }
          }

        });
      }
    // });
  }

  submit = () => {
    const{dispatch,form} = this.props;
    const{areaList,polygonList} = this.state;
     var overlays = this.map.getAllOverlays('polygon');
     //  console.log(overlays)
     // console.log(overlays[0].getPath(),1)
     // console.log(overlays[1].getPath(),2)
     // // console.log(areaList)
     // console.log(overlays[2].getPath(),3)
     //return;
        var position =  overlays;
    form.validateFields((err, values) => {
      if(!values.Address||!values.SendType||!values.AreaType) return;
      // if(err&&err.Payment){
      //   delete err.Payment
      // }

      if(err) return;

      //console.log(values,areaList)
      // for(let i=0;i<areaList.length;i++){
      //   if(areaList[i].Shape==1){
      //     if(!areaList[i].AreaName||!areaList[i].MinOrderFee||!areaList[i].FreightFee||!areaList[i].Radius){
      //       return;
      //     }
      //   }else{
      //     if(!areaList[i].AreaName||!areaList[i].MinOrderFee||!areaList[i].FreightFee){
      //       return;
      //     }
      //   }
      // }
      let param={
        AddressName:this.state.Address,
        SupportDelivery:values.SendType,
        AreaType:values.AreaType,
        SampleConfig:{},
        AreaConfig:[],
        DistanceConfig:{},
      };
      if(values.AreaType==1){
        areaList.forEach((item,index)=>{
            param.AreaConfig.push({
              Shape:item.Shape,
              Radius:item.Shape==2?null:values.Radius*1000,
              AreaName:values[`Name${index}`],
              Color:item.Color,
              Paths:[],
              MinOrderFee:values[`Price${index}`],
              FreightFee:values[`Free${index}`]
            })
            if(item.Shape==2){
              // let p=overlays[index].getPath();
              // p.forEach(v=>{
              //   param.AreaConfig[index].Paths.push([v.lng,v.lat])
              // })
              param.AreaConfig[index].Center=null;
              param.AreaConfig[index].Radius=null;
              let p = polygonList[index].He.path;
              p.forEach(v=>{
                param.AreaConfig[index].Paths.push([v.lng,v.lat])
              })
            }else{
              param.AreaConfig[index].Paths=null;
              param.AreaConfig[index].Center=[polygonList[index].He.center.lng,polygonList[index].He.center.lat];
              param.AreaConfig[index].Radius=polygonList[index].He.radius;
            }
        })
        param.SampleConfig=null;
        param.DistanceConfig=null;
      }else if(values.AreaType==2){
        param.DistanceConfig.Areas=[];
        param.DistanceConfig.FirstDistance=values.Distance;
        param.DistanceConfig.FirstFee=values.DeliveryFee;
        param.DistanceConfig.AdditionalDistance=values.AddedDistance;
        param.DistanceConfig.AdditionalFee=values.AddedDeliveryFee;
        areaList.forEach((item,index)=>{
            param.DistanceConfig.Areas.push({
              Shape:values.Shape,
              Radius:values.Shape==2?null:values.Radius*1000,
              AreaName:values[`Name${index}`],
              Color:item.Color,
              Paths:[],
              MinOrderFee:values[`Price${index}`],
             // FreightFee:values[`Free${index}`]
            })
            if(item.Shape==2){
              // let p=overlays[index].getPath();
              // p.forEach(v=>{
              //   param.AreaConfig[index].Paths.push([v.lng,v.lat])
              // })
              param.DistanceConfig[index].Center=null;
              param.DistanceConfig[index].Radius=null;
              let p = polygonList[index].He.path;
              p.forEach(v=>{
                param.DistanceConfig.Areas[index].Paths.push([v.lng,v.lat])
              })
            }else{
              param.DistanceConfig.Areas[index].Paths=null;
              param.DistanceConfig.Areas[index].Center=[polygonList[index].He.center.lng,polygonList[index].He.center.lat];
              param.DistanceConfig.Areas[index].Radius=polygonList[index].He.radius;
            }
        })
        param.SampleConfig=null;
        param.AreaConfig=null;
      }else{
         param={
          AddressName:this.state.Address,
          SupportDelivery:values.SendType,
          AreaType:values.AreaType,
          SampleConfig:{
            Name:values.SendRangeName,
            Desc:values.SendRangeDesc ,
            AreaImage:values.SendRangePic ,
            MinOrderFee:values.MinPrice ,
            FreightFee:values.SendFree
          },
          AreaConfig:null,
          DistanceConfig:null,
        };

      }
      //console.log(param,values,position)
      //return;
      dispatch({
        type: `${namespace}/SaveSameCityConfig`,
        payload: param,
        callback: {
          success: (data) => {
            message.success("保存成功");
          },
          error: (data) => {
            message.error("保存失败：" + data.Msg);
          }
        }

      });
    })
  }

  randomColor = ()=> {
    const {areaList,colorList} = this.state;
    let random = Math.ceil(Math.random()*10)-1;
    let color = colorList[random];
    let index=areaList.findIndex(v=>v.Color===color);
    if(index>-1){
      return color= this.randomColor()
    }else{
      return color;
    }
  }

  // 添加区域
  addArea = () => {
      const {areaList,polygonList,colorList,currentIndex,currenrCenter} = this.state;
      const {form} = this.props;
     // let index = `${currentIndex}`-0;
      let AreaType= form.getFieldValue('AreaType');
      let Shape = form.getFieldValue('Shape');
      let color = this.randomColor();
      let that=this;
      let path = [
          [116.391262,39.920163],
          [116.403322,39.920255],
          [116.413879,39.920492],
          [116.414737,39.89255],
          [116.402292,39.892353],
          [116.391734,39.892155]
      ];
      if(Shape==1){
        areaList.push({
          Shape:Shape,
          Center:currenrCenter||[116.433322, 39.900255],
          Radius:1,
          AreaName: undefined,
          Color: color,
          FreightFee: undefined,
          MinOrderFee: undefined,
          Paths:null
        })
      }else{
        if(currenrCenter){
          path=[
            [currenrCenter[0]+0.01,currenrCenter[1]+0.01],
            [currenrCenter[0]-0.01,currenrCenter[1]+0.01],
           // [currenrCenter[0]-0.01,currenrCenter[1]],
            [currenrCenter[0]-0.01,currenrCenter[1]-0.01],
            [currenrCenter[0]+0.01,currenrCenter[1]-0.01],
           // [currenrCenter[0]+0.01,currenrCenter[1]],
          ]
        }
        areaList.push({
          Shape:Shape,
          Center:null,
          Radius:null,
          AreaName: undefined,
          Color: color,
          FreightFee: undefined,
          MinOrderFee: undefined,
          Paths:path
        })
      }
      this.setState({
          areaList,
         // currentIndex:areaList.length-1,
      },()=>{
       this.newPolygon(areaList.length-1)
      })
  }

  newPolygon = (index) => {
    const { areaList,bgcolors,colors,colorList,areaType} = this.state;
    let that = this;
    let markers = [];
    let polygonList = [];
    let polyEditorList = [];
    this.map.clearMap();
    for (let i = 0; i < areaList.length; i++) {
        let item=areaList[i];
        let paths = item.Paths;
        let colorIndex = colorList.indexOf(item.Color);
        // 创建点实例
       // getFieldValue('Shape')===1
        if(item.Shape==1){
          let circle = new AMap.Circle({
              center: item.Center||[116.433322, 39.900255],
              radius: item.Radius*1000||1000, //半径
              borderWeight: 3,
              strokeColor: colors[colorIndex],
              strokeOpacity: 1,
              strokeWeight: 3,
              //strokeOpacity: 0.2,
              fillOpacity: 0.4,
             // strokeStyle: 'dashed',
             // strokeDasharray: [10, 10],
              // 线样式还支持 'dashed'
              fillColor: bgcolors[colorIndex],
              zIndex: 50,
              draggable: true,
              extData: {
                  id: i
              }
          })

          // that.props.form.setFieldsValue({
          //     Radius:item.Radius*1000||1000
          //   })

          // circle.setMap(that.map)
          // // 缩放地图到合适的视野级别
          // that.map.setFitView([ circle ])

          let circleEditor = new AMap.CircleEditor(that.map, circle);
          polygonList.push(circle)
          polyEditorList.push(circleEditor)
          markers.push(circle);
          circle.on('click', function(e){
            const {polyEditorList} = that.state;
            let id= e.target.B.extData.id;
            polyEditorList.forEach(v=>{
              v.close()
            })
            polyEditorList[id].open();
            that.setState({
              currentIndex:id
            })
            that.props.form.setFieldsValue({
              Shape:item.Shape
            })
            if(item.Radius){
              setTimeout(()=>{
                that.props.form.setFieldsValue({
                  Radius:e.target.He.radius/1000
                })
              },300)
            }
            that.map.setFitView(polygonList[id||0])
          });
          circleEditor.on('move', function(e) {
            console.log('move',e)
            const {areaList} = that.state;
            let id= e.target.He.extData.id;
            areaList[id].Center= [e.target.He.center.lng,e.target.He.center.lat];
            that.setState({
              areaList
            })
          })
          circleEditor.on('adjust', function(e) {
            console.log('adjust')
            const {areaList} = that.state;
            let id= e.target.B.extData.id;
            areaList[id].Radius= e.target.He.radius;
            that.setState({
              areaList
            })
            that.props.form.setFieldsValue({
              Radius:e.target.He.radius/1000
            })
          })
        }else{
          let polygon = new AMap.Polygon({
              path: paths,
              strokeColor: colors[colorIndex],
              strokeWeight: 3,
              strokeOpacity: 1,
              fillOpacity: 0.5,
              fillColor: bgcolors[colorIndex],
              zIndex: 50,
              draggable: true,
              extData: {
                  id: i
              }
          })
          polygon.on('dragging', (e)=>{
            let id= e.target.He.extData.id;
            const {polygonList} = this.state;
            polygonList[id]=e.target;
            let arr=[],path=e.target.He.path;
            path.forEach((v)=>{
              arr.push([v.lng,v.lat])
            })
            areaList[id].Paths= arr;
            that.setState({
              areaList,
              polygonList
            })
          });
          let polyEditor = new AMap.PolyEditor(that.map, polygon);
          polygonList.push(polygon)
          polyEditorList.push(polyEditor)
          markers.push(polygon);
          polygon.on('click', function(e){
            const {polyEditorList} = that.state;
            let id= e.target.B.extData.id;
            polyEditorList.forEach(v=>{
              v.close()
            })
            polyEditorList[id].open();
            that.setState({
              currentIndex:id
            })
            that.props.form.setFieldsValue({
              Shape:item.Shape
            })
            that.map.setFitView(polygonList[id||0])
          });
        }
    }
    // 创建覆盖物群组，并将 marker 传给 OverlayGroup
    var overlayGroups = new AMap.OverlayGroup(markers);
    this.map.add(overlayGroups);
    this.map.setFitView(polygonList[index||0])
    this.setState({
      polygonList,
      polyEditorList,
      currentIndex:index
    },()=>{
      let polyEditor = polyEditorList[index||0]
      polyEditor.open();
      if(areaList[index].Shape==1){
        this.props.form.setFieldsValue({
          Radius:areaList[index].Radius
        })
      }
    })
    areaList.forEach((v,i)=>{
      if(areaType==1){
        this.props.form.setFieldsValue({
          [`Name${i}`]:v.AreaName,
          [`Price${i}`]:v.MinOrderFee,
          [`Free${i}`]:v.FreightFee
        })
      }else if(areaType==2){
        this.props.form.setFieldsValue({
          [`Name${i}`]:v.AreaName,
          [`Price${i}`]:v.MinOrderFee,
          Distance:v.FirstDistance,
          DeliveryFee:v.FirstFee,
          AddedDistance:v.AdditionalDistance,
          AddedDeliveryFee:v.AdditionalFee
        })
      }
    })
  }

  // 删除区域
  deleteArea = (index,e) => {
    e.stopPropagation();
    const {areaList,currentIndex,colorList} = this.state;
    let color = colorList[currentIndex];
    areaList.splice(index,1);
    this.setState({
        areaList
    },()=>{
      const {areaList} = this.state;
      let idx= areaList.findIndex(v=>v.Color===color);
      if(idx<0){
          idx=currentIndex>areaList.length-1?areaList.length-1:currentIndex;
      }
      this.newPolygon(idx)
    })
  }

  // 配送区域设置
  areaSettings = (e) => {
   // const { form } = this.props;
   // const { areaList } = this.state;
    let type=e.target.value;
    //let oldValue=form.getFieldValue('AreaType');
    //console.log(e,oldValue)
    this.setState({
      areaType:type
    },()=>{
      const {currentIndex} = this.state;
      // if(oldValue==3){
      //   setTimeout(() => {
      //     form.setFieldsValue({
      //       Shape:areaList[currentIndex].Shape,
      //       Radius: areaList[currentIndex].Radius
      //     })
      //     this.newMap();
          this.newPolygon(currentIndex)
      //   }, 300);
      // }
    })
  }

  // 修改收货地址
  editArea = () => {
    this.Region.showModal();
  }

  //
  areaConfirm = (param) => {
    console.log(param)
    const { dispatch,form } = this.props;
    dispatch({
      type:"sameCityDelivery/SaveIntraCityAddress",
      payload:param,
      callback:{
        success:(data)=>{
          this.Region.hideModal()
          this.setState({
            Address:`${param.Prov}${param.City}${param.District}${param.Address}`
          })
          form.setFieldsValue({
            Address:`${param.Prov}${param.City}${param.District}${param.Address}`
          })
          message.success('保存成功')
        },
        error:(data)=>{
          message.error(data.Msg)
        }
      }
    })
  }

  // 选中
  selectItem = (index) => {
    const { polyEditorList ,polygonList,areaList} = this.state;
    this.setState({
      currentIndex:index
    })
    polyEditorList.forEach(v=>{
      v.close()
    })
    polyEditorList[index].open();
    if(areaList[index].Shape==1){
       this.props.form.setFieldsValue({
        Shape:areaList[index].Shape,
        Radius:areaList[index].Radius
      })
    }else{
       this.props.form.setFieldsValue({
        Shape:areaList[index].Shape
      })
    }
    this.map.setFitView(polygonList[index||0])
  }

  // limitDecimals = (value) => {
  //   const reg = /^(\-)*(\d+)\.(\d\d\d).*$/;
  //   if(typeof value === 'string') {
  //       return !isNaN(Number(value)) ? value.replace(reg, '$1$2.$3') : ''
  //   } else if (typeof value === 'number') {
  //       return !isNaN(value) ? String(value).replace(reg, '$1$2.$3') : ''
  //   } else {
  //       return ''
  //   }
  // };

  changeShape = (e) => {
    let value=e.target.value;
    const {areaList,currentIndex,colorList,currenrCenter} = this.state;
    areaList[currentIndex].Shape=value;
    if(value==1){
      areaList[currentIndex].Center= currenrCenter||[116.433322, 39.900256];
      areaList[currentIndex].Radius= 1;
    }else{
      let path = [
          [116.391262,39.920163],
          [116.403322,39.920255],
          [116.413879,39.920492],
          [116.414737,39.89255],
          [116.402292,39.892353],
          [116.391734,39.892155]
      ];
      if(currenrCenter){
          path=[
            [currenrCenter[0]+0.01,currenrCenter[1]+0.01],
            [currenrCenter[0]-0.01,currenrCenter[1]+0.01],
           // [currenrCenter[0]-0.01,currenrCenter[1]],
            [currenrCenter[0]-0.01,currenrCenter[1]-0.01],
            [currenrCenter[0]+0.01,currenrCenter[1]-0.01],
           // [currenrCenter[0]+0.01,currenrCenter[1]],
          ]
        }
      areaList[currentIndex].Paths= path;
      // areaList[currentIndex].Center= null;
      // areaList[currentIndex].Radius= null;
    }
    this.setState({
        areaList
    },()=>{
      // const {areaList} = this.state;
      // let idx= areaList.findIndex(v=>v.Color===color);
      // if(idx<0){
      //     idx=currentIndex>areaList.length-1?areaList.length-1:currentIndex;
      // }
      this.newPolygon(currentIndex)
      this.props.form.setFieldsValue({
        Radius:areaList[currentIndex].Radius,
      })
    })
  }

  changeRadius = (e) => {
    // let value=e.target.value;
    //  const {areaList,currentIndex,colorList} = this.state;
    // areaList[currentIndex].Radius= value-0;
    // console.log(value)
    //   this.setState({
    //     areaList
    // },()=>{
    //   this.newPolygon(currentIndex)
    // })
  }

  blurRadius = (e) =>{
    let value=e.target.value;
    let patrn = /^\d+(\.\d{1,3})?$/;
    if (!patrn.test(value)) {
      message.error("只能输入0.1~999之间的数字");
      return ;
    }
     const {areaList,currentIndex,colorList} = this.state;
    areaList[currentIndex].Radius= value-0;
    console.log(value)
      this.setState({
        areaList
    },()=>{
      this.newPolygon(currentIndex)
    })
  }

  onKeyPress = (e) => {
    // let value=e.target.value;
    // console.log(value,888)
    // let patrn = /^\d+(\.\d{1,3})?$/;
    // if (!patrn.test(value)) {
    //   //message.error("请输入正确的数字");
    //   return e.target.value=value.replace(/[^\d]/g,'')
    // }

    return
    console.log()
  }

  limitDecimals = (value) => {
    const reg = /^(\-)*(\d+)\.(\d\d\d).*$/;
    if(typeof value === 'string') {
        return !isNaN(Number(value)) ? value.replace(reg, '$1$2.$3') : ''
    } else if (typeof value === 'number') {
        return !isNaN(value) ? String(value).replace(reg, '$1$2.$3') : ''
    } else {
        return ''
    }
  };

   limitDecimals2 = (value) => {
    const reg = /^(\-)*(\d+)\.(\d\d).*$/;
    if(typeof value === 'string') {
        return !isNaN(Number(value)) ? value.replace(reg, '$1$2.$3') : ''
    } else if (typeof value === 'number') {
        return !isNaN(value) ? String(value).replace(reg, '$1$2.$3') : ''
    } else {
        return ''
    }
  };

  changeInput = (index,e,key) => {
    let value=e&&e.target?e.target.value:e;
     const {areaList,currentIndex} = this.state;
    areaList[index][key]= value;
      this.setState({
        areaList
    },()=>{
      this.newPolygon(currentIndex)
    })
  }

  imgModals = ref => {
    this.imgmodal = ref;
  };

  onImageChange = (param) => {
    console.log(param)
    this.setState({
      imageUrl:param.imageUrl
    })
    this.props.form.setFieldsValue({
      SendRangePic: param.imageUrl
    })
    this.imgmodal.handleModalVisible();
  }

  OpenImageModal = () => {
    this.imgmodal.handleShowModal();
  };

  handleTableChange = (pagination, filters, sorter)=>{
    this.setState(
      {
        paginationProps: {
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: false,
          showTotal: total => `共 ${total} 条记录`,
          pageIndex: pagination.current,
        },

      },()=>{
        this.GetDeliveryManPageList();
      })
  }
  deleteMan = (id) => {
    let arr=[];
    arr.push(id)
    const { dispatch } = this.props;
    dispatch({
      type: `localdelivery/DeleteMan`,
      payload: arr.toString(),
      callBack: {
        success: (data) => {
          message.success("删除成功");
          this.GetDeliveryManPageList();
        },
        error: (data) => {
          message.error("删除失败：" + data.Msg);
        }
      }
    });
  }


  render() {
    const formItemLayout = {
      labelCol: {
        xs: { span: 3 },
        sm: { span: 3 },
        md: { span: 3 },

      },
      wrapperCol: {
        xs: { span: 21 },
        sm: { span: 21 },
        md: { span: 21 },
      },
    };
    const formItemLayout2 = {
        labelCol: {
          xs: { span: 8 },
          sm: { span: 8 },
          md: { span: 8 },

        },
        wrapperCol: {
          xs: { span: 16 },
          sm: { span: 16 },
          md: { span: 16 },
        },
      };
      const columns = [{
        title: '配送员姓名',
        dataIndex: 'UserName',
        align:'left',
        key: 'UserName',
      }, {
        title: '联系方式',
        dataIndex: 'UserPhone',
        align:'left',
        key: 'UserPhone',
      }, {
        title: '创建时间',
        align:'left',
        dataIndex: 'AddTime',
        key: 'AddTime',
      }, {
        title: '操作 ',
        align:'right',
        render: (text, record )=>{
          return <div className={styles.setting}>
            <Popconfirm title="确定删除？" onConfirm={()=>this.deleteMan(record.Id)} okText="确定" cancelText="取消">
              <a href="javascript:void(0)">删除</a>
            </Popconfirm>
          </div>
        }
      }];
    const {
      getFieldDecorator, getFieldsError, getFieldError, isFieldTouched, getFieldValue
    } = this.props.form;
    const { areaList , areaType,Address,imageUrl,currentIndex,colorList,colors,paginationProps,modalVisible } = this.state;
    const { sameCityConfig, loadBtn, loading,loading2, submitLoading, deliveryLoading, deliveryManPageList,dispatch } = this.props;

    const listData = [{ name: '213123' }, { name: '213123' }, { name: '213123' }, { name: '213123' }];
    const uploadButton = (
      <div >
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    //console.log(deliveryLoading)

    return (
      <Fragment>
        <Spin spinning={loading||loading2} >
          <Card
            title="同城配送功能"
            bordered={false}
            className={styles.ExpressTitle}
          >
            <div>
                启用后，买家下单可以选择同城配送，由你提供上门配送服务。<a>查看【同城配送】功能使用教程</a>
            </div>
            <Switch
              onChange={this.setExpressConfig}
              checked={sameCityConfig && sameCityConfig.Enable ? true : false}
              defaultChecked={sameCityConfig && sameCityConfig.Enable ? true : false}
            />
          </Card>
          <Card
            title="同城配送设置"
            bordered={false}
            className={styles.ExpressSet}
          >
            <Form >
              <FormItem
                {...formItemLayout}
                label="支付方式"
               // help="请选择至少一种支付方式"
              >
                {getFieldDecorator('Payment', {
                  rules: [{ required: true, message: '请选择至少一种支付方式!' }],
                })(
                  <Checkbox.Group >
                    <Checkbox value={1}>微信支付</Checkbox>
                    <Checkbox value={2}>货到付款</Checkbox>
                  </Checkbox.Group>
                )}

              </FormItem>

              <Row>
                <Col offset={3}>
                  <Button
                    type="primary"
                    // htmlType="submit"
                    loading={loadBtn}
                    onClick={this.handleSubmit}
                  >
                    保存
                </Button>
                </Col>
              </Row>
            </Form>
          </Card>
          <Card
            title="配送详情设置"
          >
             <Form >
              <FormItem
                {...formItemLayout}
                label="取货地址"
              >
                {getFieldDecorator('Address', {
                  rules: [{ required: true, message: '请选择取货地址!' }],
                })(
                  <div>
                      {Address?<span className="xkd-mr24">{Address}</span>:null}<a onClick={this.editArea}>修改</a>
                  </div>
                )}

              </FormItem>
              <FormItem
                {...formItemLayout}
                label="配送方式"
              >
                {getFieldDecorator('SendType', {
                  initialValue:[1],
                  rules: [{ required: true, message: '请选择至少一种配送方式!' }],
                })(
                  <Checkbox.Group style={{marginTop:10,width:"100%"}}>
                    <div><Checkbox value={1} disabled>商家自配送</Checkbox>
                      <a href="javascript:void(0)" style={{marginLeft:16}} onClick={()=>this.Delivery.handelManModal(true)}>添加配送员</a>
                    </div>
                    <div style={{marginTop:16}} className={styles.deliveryMan}>
                      <div style={{marginBottom:16}}>已有配送员：</div>
                      <Spin spinning={false} >
                        <Table
                          width="100%"
                          bordered={false}
                          loading={deliveryLoading}
                          rowKey={record => record.Id}
                          dataSource={deliveryManPageList.DataList}
                          columns={columns}
                          onChange={this.handleTableChange}
                          pagination={{
                            ...paginationProps
                          }}
                        />
                      </Spin>
                    </div>
                    {/* <div style={{marginTop:10}}><Checkbox value={2}>第三方配送</Checkbox></div>                    */}
                  </Checkbox.Group>
                )}

              </FormItem>
              <FormItem
                {...formItemLayout}
                label="配送区域设置"
              >
                {getFieldDecorator('AreaType', {
                  initialValue:areaType,
                 // rules: [{ required: true, message: '请选择至少一种支付方式!' }],
                })(
                  <Radio.Group onChange={this.areaSettings} >
                    <Radio value={1}>不同区域不同配送费</Radio>
                    <Radio value={2}>不同距离不同配送费</Radio>
                    <Radio value={3}>简易版</Radio>
                  </Radio.Group>
                )}
              </FormItem>
              <Row style={{display:areaType==1||areaType==2?'block':'none'}}>
                    <Col offset={3} className={`${styles.mapContainer} ${styles.mapContainer1}`}>
                        {/* <div style={{paddingLeft:areaList&&areaList.length>0?200:0}}>
                          <div id="mapContainer" style={{width:areaList&&areaList.length>0?640:840,height:504}}></div>
                        </div> */}
                        <div id="mapContainer" style={{width:840,height:504}}></div>
                        <div style={{position:'absolute',top:16,left:16,width:200,height:(areaType==1&&areaList.length>1)||areaType==2?'calc(100% - 32px)':'auto',overflow:'hidden',boxShadow: "0 0 5px #afafaf"}}>
                            <div style={{width:217,height:'100%',overflowY:'scroll',overflowX:"hidden"}}>
                                {
                                  areaType==2?(
                                  <div className="xkd-pad16 xkd-bg-fff xkd-text-center" style={{borderBottom:"1px solid #e8e8e8"}}>
                                    <Row><Col className="xkd-text-left"><span>配送费：</span></Col></Row>
                                    <Row>
                                      <Col span={18}>
                                        <FormItem
                                            //{...formItemLayout}
                                            // labelCol={{span:8}}
                                            // wrapperCol={{span:14}}
                                           // label="配送费"
                                        >
                                            {getFieldDecorator('Distance', {
                                              rules: [{ required: true, message: '此项为必填项' }],
                                            })(
                                                <Input addonAfter={'km'}/>
                                            )}
                                        </FormItem>
                                      </Col>
                                      <Col span={6}><span style={{lineHeight:'40px'}}>内，</span></Col>
                                    </Row>
                                    <Row>
                                      <Col span={18}>
                                        <FormItem
                                            //{...formItemLayout}
                                            // labelCol={{span:7}}
                                            // wrapperCol={{span:17}}
                                        >
                                            {getFieldDecorator('DeliveryFee', {
                                              rules: [{ required: true, message: '此项为必填项' }],
                                            })(
                                                <Input addonAfter={'元'}/>
                                            )}
                                        </FormItem>
                                      </Col>
                                    </Row>
                                    <Row>
                                      <Col span={7}><span style={{lineHeight:'40px'}}>每增加</span></Col>
                                      <Col span={17}>
                                        <FormItem
                                            //{...formItemLayout}
                                            // labelCol={{span:7}}
                                            // wrapperCol={{span:14}}
                                        >
                                            {getFieldDecorator('AddedDistance', {
                                              rules: [{ required: true, message: '此项为必填项' }],
                                            })(
                                                <Input addonAfter={'km'}/>
                                            )}
                                        </FormItem>
                                      </Col>
                                    </Row>
                                    <Row>
                                      <Col span={10}><span style={{lineHeight:'40px'}}>配送费增加</span></Col>
                                      <Col span={14}>
                                        <FormItem
                                            //{...formItemLayout}
                                            // labelCol={{span:7}}
                                            // wrapperCol={{span:14}}
                                        >

                                            {getFieldDecorator('AddedDeliveryFee', {
                                              rules: [{ required: true, message: '此项为必填项' }],
                                            })(
                                                <Input addonAfter={'元'}/>
                                            )}
                                        </FormItem>
                                      </Col>
                                    </Row>
                                    <Row>
                                        <Col className="xkd-text-left xkd-color-primary">
                                        注：因考虑实际送货路况，配送费计算按步行距离，非地图直线距离
                                        </Col>
                                    </Row>
                                  </div>
                                  ):null
                                }
                                {
                                  areaType==3?null:(
                                    <List
                                    grid={{ gutter: 0, column: 1 }}
                                    dataSource={areaList}
                                    renderItem={(item,index) => (
                                    <List.Item style={{marginBottom:0}}>
                                        <Card className={`${styles.cardBorder} ${index===currentIndex?styles.active:''}`} onClick={()=>this.selectItem(index)}>
                                            <Row>
                                                <Col span={3} style={{lineHeight:'46px'}}><Tag  style={{width:16,height:16,borderRadius:0,backgroundColor:colors[colorList.indexOf(item.Color)]}}></Tag></Col>
                                                <Col span={areaList.length>1?18:21}>
                                                    <FormItem
                                                       // {...formItemLayout2}
                                                    >
                                                        {getFieldDecorator('Name'+index, {
                                                            rules: [{ required: true, message: '此项为必填项' }],
                                                        })(
                                                            <Input placeholder="请输入区域名称" onChange={(e)=>this.changeInput(index,e,`AreaName`)}/>
                                                        )}
                                                    </FormItem>
                                                </Col>
                                                {
                                                  areaList.length>1?(
                                                    <Col span={3} style={{lineHeight:'40px',textAlign:'right'}}>
                                                      <Icon
                                                        type="close"
                                                        onClick={(e)=>this.deleteArea(index,e)}
                                                      />
                                                    </Col>
                                                  ):null
                                                }
                                            </Row>
                                            <FormItem
                                                {...formItemLayout2}
                                                label="起送价"
                                                 className={styles.addonAfter2}
                                            >
                                                {getFieldDecorator('Price'+index, {
                                                rules: [{ required: true, message: '此项为必填项' }],
                                                })(
                                                    <InputNumber
                                                      min={0}
                                                      max={49999}
                                                      formatter={this.limitDecimals2}
                                                      parser={this.limitDecimals2}
                                                      onChange={(e)=>this.changeInput(index,e,`MinOrderFee`)}/>
                                                )}
                                            </FormItem>
                                            {
                                              areaType==1?(
                                                <FormItem
                                                    {...formItemLayout2}
                                                    label="配送费"
                                                    className={styles.addonAfter2}
                                                >
                                                    {getFieldDecorator('Free'+index, {
                                                    rules: [{ required: true, message: '此项为必填项' }],
                                                    })(
                                                        <InputNumber
                                                          min={0}
                                                          max={49999}
                                                          onChange={(e)=>this.changeInput(index,e,`FreightFee`)}
                                                          formatter={this.limitDecimals2}
                                                          parser={this.limitDecimals2}
                                                        />
                                                    )}
                                                </FormItem>
                                              ):null
                                            }
                                            {
                                              index===currentIndex?<Icon type="check" className={styles.activeIcon}/>:null
                                            }
                                        </Card>
                                    </List.Item>
                                    )}
                                >
                                {
                                  areaList&&areaList.length<10?(
                                    <div
                                        className="xkd-pad16 xkd-bg-fff xkd-text-center"
                                        style={{border:'1px solid #e8e8e8',borderTop:0,borderBottom:0}}
                                        onClick={this.addArea}
                                    >
                                        <div style={{border:'1px solid #2E74FF'}}><a><span>+</span>添加配送区域</a></div>
                                    </div>
                                      ):null
                                }
                                </List>
                                  )
                                }
                            </div>
                        </div>
                        <div style={{position:'absolute',top:16,left:232,width:592,height:48,paddingRight:16,overflow:'hidden',background:'#fff',boxShadow: "0 0 5px #afafaf"}}>
                            <Row>
                              <Col span={12}>
                                <FormItem
                                  label="划分方式"
                                  labelCol={{span:8}}
                                  wrapperCol={{span:16}}
                                >
                                {
                                  getFieldDecorator('Shape',{
                                    initialValue:1
                                  })(
                                    <Radio.Group onChange={this.changeShape}>
                                      <Row>
                                        <Col span={12}><Radio value={1}>半径</Radio></Col>
                                        <Col span={12}><Radio value={2}>自定义</Radio></Col>
                                      </Row>
                                    </Radio.Group>
                                  )
                                }
                                </FormItem>
                              </Col>
                              <Col span={12}>
                                <FormItem
                                  label="配送区域"
                                  labelCol={{span:8}}
                                  wrapperCol={{span:16}}
                                  className={getFieldValue('Shape')===1?styles.addonAfter:''}
                                >
                                {
                                  getFieldValue('Shape')===1?
                                  (
                                    getFieldDecorator('Radius')(
                                      <InputNumber
                                        min={0.1}
                                        max={999}
                                        //addonAfter={'公里内'}

                                        formatter={this.limitDecimals}
                                        parser={this.limitDecimals}
                                        onChange={this.changeRadius}
                                        onBlur={this.blurRadius}
                                        //onKeyUp={this.onKeyPress}


                                      />
                                    )
                                  ):(
                                    <div>区域内</div>
                                  )
                                }
                                </FormItem>
                              </Col>
                            </Row>
                        </div>
                    </Col>
                  </Row>
                  {
                    areaType==3?(
                      <div >
                    <FormItem
                      //{...formItemLayout}
                      labelCol={{span:3}}
                      wrapperCol={{span:6}}
                      label="配送范围名称"
                    >
                      {getFieldDecorator('SendRangeName', {
                        rules: [{ required: true, message: '此项为必填项' }],
                      })(
                        <Input />
                      )}
                    </FormItem>
                    <FormItem
                      //{...formItemLayout}
                      labelCol={{span:3}}
                      wrapperCol={{span:6}}
                      label="配送范围介绍"
                    >
                      {getFieldDecorator('SendRangeDesc', {
                        rules: [{ required: true, message: '此项为必填项' }],
                      })(
                        <Input.TextArea />
                      )}
                    </FormItem>
                    <FormItem
                      //{...formItemLayout}
                      labelCol={{span:3}}
                      wrapperCol={{span:6}}
                      label="配送范围图片"
                    >
                      {getFieldDecorator('SendRangePic', {
                        rules: [{ required: true, message: '此项为必填项' }],
                      })(
                        // <Upload
                        //   name="avatar"
                        //   listType="picture-card"
                        //   className="avatar-uploader"
                        //   showUploadList={false}
                        // >
                        //   {imageUrl ? <img src={imageUrl} alt="avatar" /> : uploadButton}
                        // </Upload>
                        // <div onClick={this.OpenImageModal}>
                        //   {imageUrl ? <img src={imageUrl} alt="avatar" /> : uploadButton}
                        // </div>
                        <div className={styles.uploadCover} onClick={this.OpenImageModal}>
                          {imageUrl ? <img src={`${cdnUrl}/${imageUrl}`} alt="avatar" /> : <Icon type="plus" />}
                        </div>
                      )}
                    </FormItem>
                    <FormItem
                      //{...formItemLayout}
                      labelCol={{span:3}}
                      wrapperCol={{span:6}}
                      label="起送金额"
                    >
                      {getFieldDecorator('MinPrice', {
                        rules: [{ required: true, message: '此项为必填项' }],
                      })(
                        <Input />
                      )}
                    </FormItem>
                    <FormItem
                      //{...formItemLayout}
                      labelCol={{span:3}}
                      wrapperCol={{span:6}}
                      label="配送费"
                    >
                      {getFieldDecorator('SendFree', {
                        rules: [{ required: true, message: '此项为必填项' }],
                      })(
                        <Input />
                      )}
                    </FormItem>
                  </div>
                    ):null
                  }


            </Form>

          </Card>
        </Spin>
        <div className="xkd-bottom-actions">
          <Button
            type="primary"
            onClick={this.submit}
            disabled={loading||loading2}
            loading={submitLoading}
            //disabled={id === 0 ? false : type === 1 ? loading1 : loading2}
          >
            保存
          </Button>
        </div>
        <Region onRef={(ref)=>this.Region=ref} confirm={this.areaConfirm} />
        <SelectedImage
          onRef={this.imgModals}
          selectImage={this.onImageChange}
         // checkNum={15 - this.state.list.length}
         // multiple={true}
         // limit={15}
          allUrl={false}
        />
        <DeliveryModal onRef={(ref)=>this.Delivery=ref} dispatch={dispatch} GetDeliveryManPageList={this.GetDeliveryManPageList} />
      </Fragment>
    )
  }
}
export default connect(({ sameCityDelivery, global, loading, localdelivery }) => ({
  cdnUrl: global.oemInfo.cdnUrl,
  sameCityConfig:sameCityDelivery.sameCityConfig,
  deliveryManPageList:localdelivery.deliveryManPageList,
  loading: loading.effects['sameCityDelivery/GetSameCityConfig'],
  loading2:loading.effects['sameCityDelivery/GetIntraCityAddress'],
  loadBtn: loading.effects['sameCityDelivery/SaveSameCitySupportPay'],
  submitLoading: loading.effects['sameCityDelivery/SaveSameCityConfig'],
  deliveryLoading:loading.effects['localdelivery/GetDeliveryManPageList'],
}))(Express);
